#ifndef __FORMAT_H__
#define __FORMAT_H__

#include "logLevel.hpp"
#include "util.hpp"
#include "Message.hpp"
#include <vector>
#include <cassert>
#include <iostream>
#include <sstream>
#include <memory>
namespace sqy_log
{
    class FormatItem
    {
    public:
        using ptr = std::shared_ptr<FormatItem>;
        virtual void Format(std::ostream &out, const LogMsg &msg) = 0;
    };

    class MsgFormatItem : public FormatItem // 有效消息数据
    {
    public:
        virtual void Format(std::ostream &out, const LogMsg &msg)
        {
            out << msg._payload;
        }
    };

    class LevelFormatItem : public FormatItem // 日志等级
    {
    public:
        virtual void Format(std::ostream &out, const LogMsg &msg)
        {
            out << LogLevel::toString(msg._level);
        }
    };

    class LoggerFormatItem : public FormatItem // 日志器名称
    {
    public:
        virtual void Format(std::ostream &out, const LogMsg &msg)
        {
            out << msg._logger;
        }
    };

    class ThreadFormatItem : public FormatItem // 线程ID
    {
    public:
        virtual void Format(std::ostream &out, const LogMsg &msg)
        {
            out << msg._tid;
        }
    };

    class TimeFormatItem : public FormatItem // 时间戳
    {
    public:
        TimeFormatItem(const std::string &fmt = "%H:%M:%S") : _time_fmt(fmt)
        {
        }
        virtual void Format(std::ostream &out, const LogMsg &msg)
        {
            struct tm t;
            localtime_r(&msg._ctime, &t);
            char tmp[32] = {0};
            strftime(tmp, 31, _time_fmt.c_str(), &t);
            out << tmp;
        }

    private:
        std::string _time_fmt;
    };

    class CFileFormatItem : public FormatItem // 文件名
    {
    public:
        virtual void Format(std::ostream &out, const LogMsg &msg)
        {
            out << msg._file;
        }
    };

    class LineFormatItem : public FormatItem // 行号
    {
    public:
        virtual void Format(std::ostream &out, const LogMsg &msg)
        {
            out << std::to_string(msg._line);
        }
    };

    class TabFormatItem : public FormatItem // 制表符
    {
    public:
        virtual void Format(std::ostream &out, const LogMsg &msg)
        {
            out << "\t";
        }
    };

    class NLineFormatItem : public FormatItem // 换行
    {
    public:
        virtual void Format(std::ostream &out, const LogMsg &msg)
        {
            out << "\n";
        }
    };

    class OtherFormatItem : public FormatItem // 其他
    {
    public:
        OtherFormatItem(const std::string &str = "") : _str(str)
        {
        }

        virtual void Format(std::ostream &out, const LogMsg &msg)
        {
            out << _str;
        }

    private:
        std::string _str;
    };

    // ◦ %d ⽇期
    // ◦ %T 缩进
    // ◦ %t 线程id
    // ◦ %p ⽇志级别
    // ◦ %c ⽇志器名称
    // ◦ %f ⽂件名
    // ◦ %l ⾏号
    // ◦ %m ⽇志消息
    // ◦ %n 换⾏
    class Formatter
    {
    public:
        using ptr = std::shared_ptr<Formatter>;
        Formatter(const std::string &pattern = "[%d{%H:%M:%S}][%t][%c][%f:%l][%p]%T%m%n")
            : _pattern(pattern)
        {
            assert(parsePattern());
        }
        // 对msg进行格式化
        void format(std::ostream &out, const LogMsg &msg)
        {
            for (auto &item : _items)
            {
                item->Format(out, msg); // 会根据顺序输出
            }
        }

        std::string format(const LogMsg &msg)
        {
            std::stringstream ss;
            format(ss, msg);
            return ss.str();
        }

    private:
        // 对格式化规则字符串进行解析
        bool parsePattern()
        {
            // ab%%cde[%d{%H:%M:%S}][%p]%T%m%n
            // 1.对格式化字符串进行解析处理
            std::vector<std::pair<std::string, std::string>> order;
            std::string key, val;
            size_t pos = 0;
            while (pos < _pattern.size())
            {
                // 不是%的话，那么就是原始字符串
                if (_pattern[pos] != '%') 
                {
                    val.push_back(_pattern[pos++]); 
                    continue;
                }
                // 如果是%的话，判断后面是否跟%，如果跟的话，那就是原始的%字符
                if (pos + 1 < _pattern.size() && _pattern[pos + 1] == '%')
                {
                    val.push_back(_pattern[pos + 1]);
                    pos += 2;
                    continue;
                }

                // 先进行清空
                if (!val.empty())
                {
                    order.push_back(std::make_pair("", val));
                    val.clear();
                }

                // 走到这里一定是一个格式化字符
                pos += 1;
                if (pos == _pattern.size())
                {
                    std::cout << "%之后，没有对应的格式化字符！" << std::endl;
                    return false;
                }
                key.push_back(_pattern[pos]);
                pos += 1;
                if (pos < _pattern.size() && _pattern[pos] == '{')
                {
                    pos += 1; // 让其指向'{'之后的位置
                    while (pos < _pattern.size() && _pattern[pos] != '}')
                    {
                        val.push_back(_pattern[pos]);
                        pos++;
                    }

                    if (pos == _pattern.size())
                    {
                        std::cout << "子规则{}匹配出错！" << std::endl;
                        return false;
                    }
                    pos += 1;
                }

                order.push_back(std::make_pair(key, val));
                key.clear();
                val.clear();
            }
            // 2.根据解析得到的数据初始化格式化子项数组成员
            for (auto &it : order)
            {
                _items.push_back(createItem(it.first, it.second));
            }

            return true;
        }
        // 根据不同的格式化字符串创建不同的格式化子项对象
        FormatItem::ptr createItem(const std::string &key, const std::string &val)
        {
            if (key == "d")
                return std::make_shared<TimeFormatItem>(val);
            if (key == "T")
                return std::make_shared<TabFormatItem>();
            if (key == "t")
                return std::make_shared<ThreadFormatItem>();
            if (key == "p")
                return std::make_shared<LevelFormatItem>();
            if (key == "c")
                return std::make_shared<LoggerFormatItem>();
            if (key == "f")
                return std::make_shared<CFileFormatItem>();
            if (key == "l")
                return std::make_shared<LineFormatItem>();
            if (key == "m")
                return std::make_shared<MsgFormatItem>();
            if (key == "n")
                return std::make_shared<NLineFormatItem>();
            if(key.empty()) return std::make_shared<OtherFormatItem>(val);
            std::cout << "没有对应的格式化字符：%" << key << std::endl;
            abort();
            return FormatItem::ptr();
        }

    private:
        std::string _pattern; // 格式化规则字符串
        std::vector<FormatItem::ptr> _items;
    };
}

#endif